<?php
if (!defined('INDEX') || INDEX == false) die ('Acc�s denied');

/**
 * SQL Controler
 *
 * @version 0.1
 * @copyright 2010
 */
sublib_include('SQLResult');
sublib_include('SQLRow');
/**
 * Job SQL alias SQL controler
 *
 */
class SQL extends sqld{
	private $Pwhere;
	private $table;

	/**
	 * Constructor
	 */
	function __construct($table)
	{
		$this->Pwhere = array();
		if (!is_array($table))
		{
			$this->table = array($table);
		}
		else
		{
			$this->table = $table;
		}
	}

	protected function buildTable()
	{
		if (!is_array($this->table))
		{
			return "$this->table`";
		}
		else
		{
			$table = '';
			foreach ($this->table as $key => $e){
				$table .= ', `' . $e . '`';
				if (is_string($key))
				{
					if (preg_match('`^[a-zA-Z]*$`', $key, $m))
					{
						$table .= ' AS ' . $key;
					}
					else
					{
						throw new Exception('You can\'t use no alphabetic char on a table alias.');
					}
				}
			}
			return substr($table, 2);
		}
	}

	protected function buildWhere($where)
	{
		if (count($where) == 0)
		{
			return '';
		}
		else
		{
			$str = ' WHERE';
			$nop = true;
			
			$TableKeys = array_flip($this->table);

			foreach ($where as $table => $fieldlist){
				if (!in_array($table, $this->table))
				{
					var_dump($this->table, $where);
					throw new Exception('Table in where close isn\'t in the select.');
				}
				
				if (is_string($TableKeys[$table]))
				{
					$table = $TableKeys[$table];
				}
				else
				{
					$table = '`' . addcslashes($table, '`') . '`';
				}
				
				foreach ($fieldlist as $field => $params){
					$str .= ' ';
					if ($nop)
					{
						$nop = false;
					}
					else
					{
						$str .= 'AND ';
					}
					$str .= "{$table}.{$field} $params[op] $params[value]";
				}
			}
			return $str;
		}
	}

	protected function getRowKey()
	{
		$keys = $this->getKey();
		$pkey = array_keys($this->table);
		$pkey = $this->table[$pkey[0]];
		return (isset($keys[$pkey])) ? ($keys[$pkey]) : false;

	}

	function where($where, $op = 'AND')
	{
		if (count(array_diff(array_keys($where), $this->table, array_keys($this->table))) > 0)
		{
			if (count($this->table) > 1)
			{
				throw new Exception('You can\'t use a where shemas without table index if you are in multi-table query');
			}
			else
			{
				$table = array_values($this->table);
				$where = array($table[0] => $where);
			}
		}

		foreach ($where as $table => $fields){
			foreach ($fields as $field => &$params)
			{
				if (!is_array($params))
				{
					$params = array(
						'op' => '=',
						'value' => $params,
					);
				}
				elseif (!isset($params['value']) && !isset($params['field']))
				{
					throw new Exception('the field ' . $field . ' haven\'t a value');
				}
				elseif (!isset($params['op']))
				{
					$params['op'] = '=';
				}
				elseif (!in_array($params['op'], array('=', '<', '>', '<=', '>=')))
				{
					throw new Exception('Unknow operator:' . $params['op']);
				}
				if (isset($params['value']))
				{
					$params['value'] = '\'' . $this->escape($params['value']) . '\'';
				}
				else
				{
					$params['value'] = $params['field'];
				}
			}
			if (!isset($this->Pwhere[$table]))
			{
				$this->Pwhere[$table] = $fields;
			}
			else
			{
				$this->Pwhere[$table] += $fields;
			}
		}

		return $this;
	}

	function insert($data)
	{
		if (count($this->table) > 1)
		{
			throw new Exception('You can\'t insert with multi tables or alias');
		}
		else
		{
			$query = 'INSERT INTO '.$this->buildTable() . ' (`';
			$colums = array_keys($data);
			$query = $query . implode('`, `', $colums);
			$query .= '`) VALUES (';
			foreach ($data as $value)
			{
				if ($value === null)
				{
					$query .= 'NULL,';
				}	
				else
				{
					$query .= '\'' . $this->escape($value) . '\',';
				}
			}
			$query = substr($query, 0, -1);
			$query .= ')';
			$this->query($query);
			return $this->lastID();
		}
	}

	function set($data)
	{
		if (count($this->table) > 1)
		{
			throw new Exception('You can\'t set in a view shemas');
		}
		else
		{
			$query = 'UPDATE `' . $this->table[0] . '` SET ';
			foreach ($data as $field => $value){
				$query .= '`'.addcslashes($field, '`')
					. '` = \'' . $this->escape($value) . '\',';
			}
			$query = substr($query, 0, -1);
			$query .= $this->buildWhere($this->Pwhere);
			$this->query($query);
			return $this->nbRow();
		}
	}

	function delete()
	{
		if (count($this->table) != 1)
		{
			throw new Exception('We only can delete from 1 table');
		}
		else
		{
			$query = 'DELETE FROM `' . $this->table[0]
				. $this->buildWhere($this->Pwhere);
			$this->query($query);
			return $this->nbRow();
		}
	}

	function select($colums = '*', $sufix = '')
	{
		$str = 'SELECT';
		if ($colums = '*')
		{
			$str .= ' *';
		}
		elseif (!is_array($colums))
		{
			throw new Exception('Bad paramater colums');
		}
		else
		{
			foreach ($colums as $table => $fields){
				$table = ' `' . addcslashes($table, '`') . '`';
				if ($fields == '*')
				{
					$str .= $table . '.*,';
				}
				else
				{
					$str .= $table . '.`' . implode('`'.$table.'.`', $fields) . '`,';
				}
			}
		}
		$str .= ' FROM ' . $this->buildTable();
		$where = $this->buildWhere($this->Pwhere);
		$str .= $where;
		$results = $this->query($str . $sufix);
		$pkey = array_keys($this->table);
		$pkey = $this->table[$pkey[0]];
		return new SQLReslut($results, $this->getRowKey(), $pkey);
	}

	function __destruct()
	{
		$this->freeResult();
	}
}
?>
